import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router/index.js'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        queryStr: "",
        good: {},
        cart: [],
        user: [],
        userMap: [],
        loginStatus: false
    },
    mutations: {
        setQueryStr: function (state, inputStr) {
            state.queryStr = inputStr
            // console.log(this.state.queryStr);
        },
        openDetail: function (state, good) {
            // console.log(good);
            state.good = good
            console.log(state.good)
            router.push('/details')
        },
        addIntoCart: function (state, good) {
            console.log(good);
            var ele = state.cart.find(function (ele) {
                return ele.id === good.id
            })
            if (ele) {
                ele.num++
            } else {
                state.cart.push({
                    ...good,
                    num: 1
                })
            }
            console.log(state.cart);
        },
        removeFromCart: function (state, index) {
            state.cart.splice(index, 1)
        },
        Logout:function(state){
            state.user = []
            state.loginStatus = false
        }
    },
    actions: {
        setLoginUser:function(state, user){
            console.log(user);
            var check = false
            state.rootState.userMap.forEach((ele)=>{
                if (ele.username === user.username && ele.password === user.password) {
                    check = true
                }
            })
            if (check) {
                state.rootState.user = user
                state.rootState.loginStatus = true
                console.log('success',state.rootState.user);
                console.log('success',state.loginStatus);
                return true
            }
            return false
        },
        setUserMap: function (state, userR) {
            console.log('userR', userR)
            var check = false
            for (var i = 0; i < state.rootState.userMap.length; i++) {
                if (state.rootState.userMap[i].username === userR.username) {
                    check = true
                }
                console.log('??');
            }
            if (!check) {
                state.rootState.userMap.push(userR)
                console.log('userMap', state.rootState.userMap);
                return true
            }
            return false
        }
    },
    modules: {}
})